/**
 * @Creator: fenglingxia
 * @Date: 2020/03/17
 * 「用户特征」-用户清单
 */

import React, {useContext, useCallback, useEffect, useState} from 'react';
import {QuestionCircleFilled} from '@ant-design/icons';
import {Table, Button, Pagination, message, Tooltip} from 'antd';
import {getUserList} from '~/service/performance';
import http from '~/service/http';
import constant from '~/service/constant';
import {TARGET_TYPE, TARGET_DATA_INDEX} from '~/utils/const';
import {StoreContext, generateUserListParam} from '../data';
import {USER_FEATURE_ACTION_TYPES} from '../utils';

import './index.styl';

function getContent(text, record, index) {
    return (
        <Tooltip title={text}>
            <p
                style={{
                    maxWidth: 150, overflow: 'hidden', textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                }}
            >
                {text}
            </p>
        </Tooltip>
    );
}
function getLongContent(text, record, index) {
    return (
        <Tooltip title={text}>
            <p
                style={{
                    maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap'
                }}
            >
                {text}
            </p>
        </Tooltip>
    );
}
// 用户特征——用户清单表格表头
const TABLE_HEAD = [
    {
        title: '时间',
        dataIndex: 'datetime',
        key: 'datetime_userList',
        width: 185,
        fixed: 'left',
        align: 'center'
    },
    {
        title: '用户ID',
        dataIndex: 'userId',
        key: 'userId_userList',
        width: 300,
        align: 'right',
        render: getLongContent,

    },
    {
        title: '业务线',
        dataIndex: 'bizTypeName',
        key: 'bizTypeName_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '应用',
        dataIndex: 'bizName',
        key: 'bizName_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '路径',
        dataIndex: 'path',
        key: 'path_userList',
        width: 150,
        render: getContent,
        align: 'center'

    },
    {
        title: '省份',
        dataIndex: 'province',
        key: 'province_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '城市',
        dataIndex: 'city',
        key: 'city_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '运营商',
        dataIndex: 'carrier',
        key: 'carrier_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '网络环境',
        dataIndex: 'netType',
        key: 'netType_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '操作系统',
        dataIndex: 'os',
        key: 'os_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '系统版本',
        dataIndex: 'osVersion',
        key: 'osVersion_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '用户机型',
        dataIndex: 'brandVersion',
        key: 'brandVersion_userList',
        width: 150,
        align: 'center',
        render: getContent,
    },
    {
        title: 'FSP',
        dataIndex: 'fsp',
        key: 'fsp_userList',
        width: 150,
        align: 'center',
        render: getContent,
    },
    {
        title: 'FI',
        dataIndex: 'fi',
        key: 'fi_userList',
        width: 150,
        align: 'center',
        render: getContent,
    },
    {
        title: 'FR',
        dataIndex: 'fr',
        key: 'fr_userList',
        width: 150,
        align: 'center',
        render: getContent,
    },
    {
        title: 'FIP',
        dataIndex: 'fip',
        key: 'fip_userList',
        width: 100,
        align: 'center',
        render: getContent,
    },
    {
        title: 'TTDC',
        dataIndex: 'ttdc',
        key: 'ttdc_userList',
        width: 100,
        align: 'center',
        render: getContent,
    },
    {
        title: '首屏时间',
        dataIndex: 'ttfp',
        key: 'ttfp_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '响应时间',
        dataIndex: 'resp',
        key: 'resp_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: 'Dom树解析时间',
        dataIndex: 'tree',
        key: 'tree_userList',
        width: 240,
        align: 'center',
        render: getContent,

    },
    {
        title: '页面可交互时间',
        dataIndex: 'ready',
        key: 'redy_userList',
        width: 240,
        align: 'center',
        render: getContent,

    },
    {
        title: 'TTFB',
        dataIndex: 'ttfb',
        key: 'ttfb_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: '白屏时间',
        dataIndex: 'ttsr',
        key: 'ttsr_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: 'DNS时间',
        dataIndex: 'dns',
        key: 'dns_userList',
        width: 150,
        align: 'center',
        render: getContent,

    },
    {
        title: 'TCP时间',
        dataIndex: 'tcp',
        key: 'tcp_userList',
        width: 150,
        align: 'center',
        render: getContent,
    }
];

export default () => {
    const {state, dispatch} = useContext(StoreContext);
    const {pager: {count, pageNum, pageSize}, userListResult} = state.userListData;
    const {userListLoading, targetType} = state;

    // 当改变页码时
    function onChange(pageNum, pageSize) {
        dispatch({
            type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
            payload: {
                userListData: {
                    pager: {
                        pageNum,
                        pageSize,
                        count
                    }
                }
            },
        });
    }
    // 当改变每页显示的条数时，重置页码为第一页
    function onShowSizeChange(current, size) {
        dispatch({
            type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
            payload: {
                userListData: {
                    pager: {
                        pageNum: 1,
                        pageSize: size,
                        count
                    }
                }
            },
        });
    }
    const basicParam = generateUserListParam(state);
    // 定义下载的loading
    const [downLoading, setDownLoading] = useState(false);
    // 下载明细数据
    const downloadDataList = useCallback(() => {

        if (userListResult.length > 0) {
            setDownLoading(true);
            http({
                url: constant.PERFORMANCE.DOWNLOAD_USER_LIST,
                method: 'post',
                data: {
                    ...basicParam
                },
                responseType: 'blob'
            }).then(res => {
                const blob = new Blob([res], {
                    type: 'application/vnd.ms-excel;'
                });
                const downloadElement = document.createElement('a');
                const href = window.URL.createObjectURL(blob);
                downloadElement.href = href;
                const time = (new Date()).getTime();
                downloadElement.download = `用户清单${time}.xlsx`;
                document.body.appendChild(downloadElement);
                downloadElement.click();
                document.body.removeChild(downloadElement);
                window.URL.revokeObjectURL(href);
                setDownLoading(false);
            });

        }
        else {
            message.warn('用户清单列表为空');
        }
    });
    // 当pageSize和pageNum改变时执行
    useEffect(() => {
        if (count > 0) {
            (async () => {
                dispatch({
                    type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                    payload: {
                        userListLoading: true
                    },
                });
                const userListData = await getUserList(
                    {
                        ...basicParam,
                        pager: {pageNum, pageSize}
                    }
                );
                if (userListData?.data?.userDetails) {
                    const data = userListData.data.userDetails.map((item, index) => ({
                        ...item,
                        key: `key${index}`
                    }));

                    dispatch({
                        type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                        payload: {
                            userListData: {
                                userListResult: data,
                                pager: userListData?.pager
                            },
                            userListLoading: false
                        },
                    });
                }

            })();
        }
    }, [pageNum, pageSize]);
    return (
        <div className="user-list">
            <div className="table-header">
                <div>
                    <h3>用户清单</h3>
                    <Tooltip title="仅保留近30天的明细数据，最多支持查询或下载距离筛选结束时间7天以内的数据，如果数据超过10万条，截取最近的10万条数据。">
                        <QuestionCircleFilled style={{marginLeft: 12}} />
                    </Tooltip>
                </div>
                <Button type="primary" onClick={downloadDataList} loading={downLoading}>下载</Button>
            </div>
            <Table
                columns={TABLE_HEAD}
                dataSource={userListResult}
                pagination={false}
                loading={userListLoading}
                scroll={{x: 2500}}
            />
            <Pagination
                className="userList-pagination"
                showSizeChanger
                onShowSizeChange={onShowSizeChange}
                onChange={onChange}
                current={pageNum}
                pageSize={pageSize}
                total={count}
                defaultPageSize={10}
                pageSizeOptions={['10', '20', '50', '100']}
                id="userListPagination"
            />
        </div>
    );
};
